package com.summer.data.spring;

import com.summer.data.Jsql;
import com.summer.data.rs.extractor.KeysExtractor;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.SqlProvider;
import org.springframework.util.Assert;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author 345480567@qq.com
 */
class JsqlPreparedStatementCreator implements PreparedStatementCreator, SqlProvider {

    private final Jsql jsql;

    private final KeysExtractor keysExtractor;

    public JsqlPreparedStatementCreator(Jsql jsql, KeysExtractor keysExtractor) {
        Assert.notNull(jsql, "Jsql must not be null");
        this.jsql = jsql;
        this.keysExtractor = keysExtractor;
    }

    @Override
    public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
        if (keysExtractor == null) {
            return con.prepareStatement(this.jsql.getString(), Statement.NO_GENERATED_KEYS);
//            ps = conn.prepareStatement(sqlString, Statement.NO_GENERATED_KEYS);
        } else {
            // ps = conn.prepareStatement(sqlString, Statement.RETURN_GENERATED_KEYS);
//            ps = conn.prepareStatement(sqlString, keysExtractor.getKeys());
            return con.prepareStatement(this.jsql.getString(), Statement.RETURN_GENERATED_KEYS);
        }
    }

    @Override
    public String getSql() {
        return this.jsql.getString();
    }
}
